#include<bits/stdc++.h>
#define ll long long
#define ull unsigned long long
using namespace std;

const int N = 1e5 + 10, INF = 0x3f3f3f3f;

int n, m, tt;
struct node {
    int x, y;
}st[N];

bool check1()
{
    for (int i = 1;i <= tt;i++) if (st[i].x != st[1].x) return 0;
    return 1;
}

bool check2()
{
    for (int i = 1;i <= tt;i++) if (st[i].y != st[1].y) return 0;
    return 1;
}

bool check3()
{
    int flag1 = 1, flag2 = 1;
    int t1 = 0, t2 = 0;
    for (int i = 1;i <= tt && t1 == 0;i++)
        for (int j = i + 1;j <= tt && t1 == 0;j++)
            if (st[i].x != st[j].x && st[i].y != st[j].y) t1 = i, t2 = j;

    int mx = st[t1].x, my = st[t2].y;
    for (int i = 1;i <= tt;i++)
        if (st[i].x != mx && st[i].y != my) { flag1 = 0; break; }

    mx = st[t2].x, my = st[t1].y;
    for (int i = 1;i <= tt;i++)
        if (st[i].x != mx && st[i].y != my) { flag2 = 0; break; }
    return flag1 || flag2;
}

void solve()
{
    int mx = -1;
    cin >> n >> m;
    tt = 0;
    for (int i = 1;i <= n;i++)
        for (int j = 1;j <= m;j++) {
            int x;cin >> x;
            if (x == mx) {
                ++tt;
                st[tt].x = i;
                st[tt].y = j;
            } else if (x > mx) {
                tt = 1;
                st[tt].x = i;
                st[tt].y = j;
                mx = max(mx, x);
            }
        }

    if (tt == 1 || check1() || check2() || check3()) cout << mx - 1 << '\n';
    else cout << mx << '\n';
}

signed main()
{
    // ios::sync_with_stdio(0);
    // cin.tie(0);cout.tie(0);
// #define ONLINE_JUDGE
#ifndef ONLINE_JUDGE
    std::istringstream in(R"()");
    std::cin.rdbuf(in.rdbuf());
#endif
    int T = 1;
    cin >> T;
    for (int i = 1;i <= T;i++) {
        solve();
    }
}